/**
 * 
 */
package com.tvt.sexyapp_demo.downloader;

import java.io.InputStream;
import java.util.ArrayList;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;

import com.tvt.sexyapp_demo.appconfig.manager.PageInfoManager;
import com.tvt.sexyapp_demo.appconfig.xml.XItem;
import com.tvt.sexyapp_demo.callback.BaseUpdateCallback;
import com.tvt.sexyapp_demo.debug.Debug;

/**
 * @author MR_HIEU
 * 
 */
public class FileDownloaderUseAsyncTask extends
		AsyncTask<ArrayList<XItem>, Integer, ArrayList<XItem>> {

	private final String LOG_TAG = this.getClass().getSimpleName();

	// Fields
	private BaseUpdateCallback mUpdateCallback;

	public FileDownloaderUseAsyncTask(BaseUpdateCallback pUpdateCallback) {

		this.mUpdateCallback = pUpdateCallback;
	}

	// Basic interfaces
	@Override
	protected void onPreExecute() {
		super.onPreExecute();

		if (this.mUpdateCallback != null)
			this.mUpdateCallback.showLoading();
		else
			Debug.w(LOG_TAG, "Can't show loading on null callback!");
	}

	@Override
	protected ArrayList<XItem> doInBackground(ArrayList<XItem>... pXItems) {

		if (pXItems == null) {

			Debug.w(LOG_TAG, "Can't download null ArrayList(XItem)!");
			this.cancel(true);
			return null;
		}

		ArrayList<XItem> xItemsOfPage = pXItems[0];

		for (XItem xItem : xItemsOfPage) {

			InputStream is = GNetworkUtils.doExcuteByGetMethod(xItem
					.getImageUrl());

			Bitmap bitmap;
			if (is != null) {

				bitmap = BitmapFactory.decodeStream(is);
				if (bitmap != null)
					xItem.setBitmap(bitmap);
				else {
					Debug.e(LOG_TAG,
							"Can't decode bitmap for url: "
									+ xItem.getImageUrl()
									+ ", so set it to default picture!");

					xItem.setBitmap(PageInfoManager.getInstance()
							.getDefaultPicture());
				}
			} else {

				Debug.e(LOG_TAG,
						"Can't download picture for url: "
								+ xItem.getImageUrl()
								+ ", so set it to default picture!");

				xItem.setBitmap(PageInfoManager.getInstance()
						.getDefaultPicture());
			}

		}
		return xItemsOfPage;
	}

	protected void onPostExecute(ArrayList<XItem> pXItemsOfPage) {

		if (this.mUpdateCallback != null) {

			if (pXItemsOfPage != null) {

				this.mUpdateCallback.setXItemsOfPage(pXItemsOfPage);
				this.mUpdateCallback.run();

			} else
				Debug.w(LOG_TAG, "XItems is null, so can't update on callback!");

			this.mUpdateCallback.dismissLoading();

		} else {
			Debug.w(LOG_TAG, "Can't update on null callback!");
		}
	};

}
